﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace NCRGEA.Members
{
    public partial class frmAddMembers : Form
    {
        public frmAddMembers()
        {
            InitializeComponent();
        }

        private void txtSSN1_KeyUp(object sender, KeyEventArgs e)
        {
            if (txtSSN1.Text.Length == 3)
                txtSSN2.Focus();
        }

        private void txtSSN2_KeyUp(object sender, KeyEventArgs e)
        {
            if (txtSSN2.Text.Length == 2)
                txtSSN3.Focus();
        }

        private void frmAddMembers_Load(object sender, EventArgs e)
        {
            PopulateFields();
        }

        private void PopulateFields()
        {
            //Populate status types
            string qry = "SELECT TypeID, Name FROM memTypes";
            DataTable statusTypes = AAL.DAL.ExecuteQuery(qry);
            if (statusTypes != null)
            {
                cmbStatus.DataSource = statusTypes;
                cmbStatus.DisplayMember = "Name";
            }

            cmbSex.SelectedIndex = 0;
            dateDOB.MaxDate = dateRetired.MaxDate = DateTime.Now;
        }

        private void chkRetired_CheckedChanged(object sender, EventArgs e)
        {
            dateRetired.Enabled = chkRetired.Checked;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                try
                {
                    SaveData();
                }
                catch (Exception eX)
                {
                    MessageBox.Show("Error: Couldn't save new member! Information: " + eX.Message);
                    Logger.Log(eX.Message);
                }
            }
        }

        private void SaveData()
        {
            string ssn = txtSSN1.Text + txtSSN2.Text + txtSSN3.Text;
            if (string.IsNullOrWhiteSpace(ssn))
                ssn = null;
            int typeID = (int)((DataRowView)cmbStatus.SelectedValue)["TypeID"];
            DateTime dob = dateDOB.Value;
            string sex = cmbSex.Text.Substring(0, 1).ToUpper();
            string fName = txtFirstName.Text;
            string mName = txtMiddleName.Text;
            string lName = txtLastName.Text;
            string address1 = txtAddress.Text;
            string address2 = txtAddress2.Text;
            string county = txtCounty.Text;
            string city = txtCity.Text;
            string state = txtState.Text;
            string zip = txtZip.Text;
            string zipfour = txtZipFour.Text;
            string email = txtEmail.Text;
            string phone = txtPhone1.Text;
            string phone2 = txtPhone2.Text;
            string employer = txtEmployer.Text;
            DateTime retiredDate = DateTime.MinValue;
            if (chkRetired.Checked)
                retiredDate = dateRetired.Value;
            int yearsService = 0;
            if (IsInteger(txtYearsService.Text))
                yearsService = Int32.Parse(txtYearsService.Text);

            string sqlQuery = @"INSERT INTO memInfo (SSN, TypeID, DOB, Sex, FirstName, MiddleName, LastName,
                                    Address1, Address2, City, State, Zip, ZipFour, Email, Phone, Phone2, Employer,
                                    RetirementDate, YearsService, JoinDate, County)
                                VALUES (@ssn, @typeID, @dob, @sex, @fName, @mName, @lName, @address1, @address2,
                                        @city, @state, @zip, @zipfour, @email, @phone, @phone2, @employer, @retiredDate,
                                        @yearsService, @joinDate, @county)";

            SqlParameter[] sParams = new SqlParameter[21];
            sParams[0] = new SqlParameter("@ssn", AAL.DAL.DBN(ssn)) { SqlDbType = SqlDbType.VarChar, Size=9, IsNullable=true };
            sParams[1] = new SqlParameter("@typeID", typeID) { SqlDbType = SqlDbType.Int };
            sParams[2] = new SqlParameter("@dob", dob) { SqlDbType = SqlDbType.Date };
            sParams[3] = new SqlParameter("@sex", sex) { SqlDbType = SqlDbType.VarChar, Size=1 };
            sParams[4] = new SqlParameter("@fName", fName) { SqlDbType = SqlDbType.VarChar, Size= 30 };
            sParams[5] = new SqlParameter("@mName", mName) { SqlDbType = SqlDbType.VarChar, Size = 30 };
            sParams[6] = new SqlParameter("@lName", lName) { SqlDbType = SqlDbType.VarChar, Size = 30 };
            sParams[7] = new SqlParameter("@address1", address1) { SqlDbType = SqlDbType.VarChar, Size = 50 };
            sParams[8] = new SqlParameter("@address2", address2) { SqlDbType = SqlDbType.VarChar, Size = 50 };
            sParams[9] = new SqlParameter("@city", city) { SqlDbType = SqlDbType.VarChar, Size = 20 };
            sParams[10] = new SqlParameter("@state", state) { SqlDbType = SqlDbType.VarChar, Size = 20 };
            sParams[11] = new SqlParameter("@zip", zip) { SqlDbType = SqlDbType.VarChar, Size = 5 };
            sParams[12] = new SqlParameter("@zipfour", zipfour) { SqlDbType = SqlDbType.VarChar, Size = 4 };
            sParams[13] = new SqlParameter("@email", email) { SqlDbType = SqlDbType.VarChar, Size = 40 };
            sParams[14] = new SqlParameter("@phone", phone) { SqlDbType = SqlDbType.VarChar, Size = 15 };
            sParams[15] = new SqlParameter("@phone2", phone2) { SqlDbType = SqlDbType.VarChar, Size = 15 };
            sParams[16] = new SqlParameter("@employer", employer) { SqlDbType = SqlDbType.VarChar, Size = 40 };
            sParams[17] = new SqlParameter("@retiredDate", retiredDate) { SqlDbType = SqlDbType.Date};
            sParams[18] = new SqlParameter("@yearsService", yearsService) { SqlDbType = SqlDbType.SmallInt };
            sParams[19] = new SqlParameter("@joinDate", DateTime.Now) { SqlDbType = SqlDbType.Date };
            sParams[20] = new SqlParameter("@county", county) { SqlDbType = SqlDbType.VarChar, Size=20 };

            int result = AAL.DAL.ExecuteNonQuery(sqlQuery, sParams);
            if (result == 1)
            {
                UpdateSuccessful();
            }
            else
            {
                MessageBox.Show("Error creating new member!");
                Logger.Log("Couldn't created member. Rows Affected: " + result);
            }

        }

        public void UpdateSuccessful()
        {
            DialogResult dr = MessageBox.Show("Member was created! Do you want to create another?", "NCRGEA",MessageBoxButtons.YesNo);
            //if (dr == DialogResult.No)
            //    ViewMember();
            ClearForm();
        }

        public void ClearForm()
        {
            txtSSN1.Text = txtSSN2.Text = txtSSN3.Text = txtFirstName.Text = txtLastName.Text = txtMiddleName.Text = string.Empty;
            txtAddress.Text = txtAddress2.Text = txtCounty.Text = txtCity.Text = txtState.Text = txtZip.Text = txtZipFour.Text = string.Empty;
            txtEmail.Text = txtPhone1.Text = txtPhone2.Text = txtEmployer.Text = txtYearsService.Text = string.Empty;
            dateDOB.Value = dateDOB.MaxDate = DateTime.Now;
            dateRetired.Value = DateTime.Now;
            chkRetired.Checked = false;
            dateRetired.Enabled = false;
            cmbSex.SelectedIndex = 0;
            cmbStatus.SelectedIndex = 0;
        }

        //public void ViewMember()
        //{
        //    int? MemberID = AAL.UAL.GetMemberIDFromSSN(txtSSN1.Text + txtSSN2.Text + txtSSN3.Text);
        //    if (MemberID == null)
        //        MessageBox.Show("There was an error translating the SSN to a MemberID! Please note the SSN and contact your System Administrator.", "NCRGEA");
        //    else
        //    {
        //        frmMain mainForm = (frmMain)this.MdiParent;
        //        mainForm.LaunchForm(new frmViewMember(MemberID.Value));                
        //    }
        //}

        private void CheckData()
        {
            if (!string.IsNullOrWhiteSpace(txtState.Text))
                txtState.Text = txtState.Text.ToUpper();
        }

        private bool ValidateData()
        {
            //Parse over data and make any quick corrections
            CheckData();

            //Check Status
            if (cmbStatus.SelectedIndex == -1)
            {
                ShowMessageAndFocus("Please select a member status!", cmbStatus);
                return false;
            }

            //Check Sex
            if (cmbSex.SelectedIndex == -1)
            {
                ShowMessageAndFocus("Please select a member sex!", cmbSex);
                return false;
            }

            //Check First Name
            if (string.IsNullOrWhiteSpace(txtFirstName.Text))
            {
                ShowMessageAndFocus("Invalid First Name!", txtFirstName);
                return false;
            }

            //Check Last Name
            if (string.IsNullOrWhiteSpace(txtLastName.Text))
            {
                ShowMessageAndFocus("Invalid Last Name!", txtLastName);
                return false;
            }

            //Check City
            if (string.IsNullOrWhiteSpace(txtCity.Text))
            {
                ShowMessageAndFocus("Invalid City!", txtCity);
                return false;
            }

            //Check State
            if (string.IsNullOrWhiteSpace(txtState.Text) || !ValidateState(txtState.Text))
            {
                ShowMessageAndFocus("Invalid State!", txtState);
                return false;
            }

            //Check Zip (not four)
            if (string.IsNullOrWhiteSpace(txtZip.Text) || !IsInteger(txtZip.Text))
            {
                ShowMessageAndFocus("Invalid Zip!", txtZip);
                return false;
            }

            //Validate that YearsService is an integer (not required
            if (!string.IsNullOrWhiteSpace(txtYearsService.Text) && !IsInteger(txtYearsService.Text))
            {
                ShowMessageAndFocus("Invalid years of service!", txtYearsService);
                return false;
            }


            return true;
        }

        public bool ValidateState(string state)
        {
            string[] states = {"AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"};
            string uState = state.ToUpper();
            if (states.Contains(uState))
                return true;
            return false;
        }

        public void ShowMessageAndFocus(string msg, Control c)
        {
            MessageBox.Show(msg);
            if (c is TextBox)
                c.Text = string.Empty;
            c.Focus();
        }

        public bool IsInteger(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return false;
            int a;
            if (Int32.TryParse(str, out a))
                return true;
            return false;
        }
    }
}
